package com.item.read;

import com.intellij.openapi.actionSystem.*;
import com.item.read.store.SettingConfig;
import com.item.read.store.SettingState;
import com.item.read.ui.LeanENForm;
import com.item.read.util.AsynUtil;
import com.item.read.util.CacheUtils;
import com.item.read.util.JsoupHelp;
import com.item.read.vo.ContentVo;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;


public class ContentAction extends DefaultActionGroup {
    private static String path = "";
    private static List<String> content = new ArrayList();
    private static List<String> urls = null;
    private static List<String> directory = null;
    public  static AtomicInteger index = new AtomicInteger(-1);
    public  static AtomicInteger urlIndex = new AtomicInteger(-1);
    private static int urlDepth = 0;
    private static AnActionEvent anActionEvent = null;
    private static int word = 20;
    private static boolean flag = true;
    @Override
    public void update(@NotNull AnActionEvent e) {
        anActionEvent = e;
        if(content!=null && content.size() > 0) {
        }else{
                AsynUtil.submit(new Runnable() {
                    @Override
                    public void run() {
                        SettingConfig config=SettingState.getInstance().getConfig();
                        if (config == null || StringUtils.isEmpty(config.getFilePath())) {
                            return;
                        }
                        path = config.getFilePath();
                        word = config.getWordNum() <= 0?20:config.getWordNum();
                        index.set(config.getReadIndex()==0?-1:config.getReadIndex());
                        urlIndex.set(config.getUrlIndex());
                        urlDepth = config.getUrlDepth();
                        Map<String,List<String>> data = contentInit(
                                config.getFilePath()
                                ,word
                                ,config.getUrlIndex(),
                                config.getUrlDepth());
                        content = data.get("data");
                        urls    = data.get("urls");
                        directory=data.get("directory");
                    }
                });
        }
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
    }

    public static void forward(){
        if(anActionEvent==null){
            return;
        }
        if(content!=null){
            index.decrementAndGet();
            if(index.get()<0){
                if(checkTurn() && urlIndex.get() > 0){
                    SettingConfig config=SettingState.getInstance().getConfig();
                    config.setUrlIndex(urlIndex.decrementAndGet());
                    if(CacheUtils.get(urlIndex.get())!=null){
                        content = CacheUtils.get(urlIndex.get());
                    }else{
                        content = getUrlData(word,urlIndex.get(),urls);
                        CacheUtils.add(urlIndex.get(),content);
                    }
                    config.setReadIndex(content.size()-1);
                    index.set(content.size()-1);
                }else{
                    return;
                }
            }
            setText(content.get(index.get()));
            saveReadIndex();
        }
    }
    public static void next(){
        if(anActionEvent==null){
            return;
        }
        if(content!=null && index.get() >=-1){
            if(index.get() == content.size()-1){
                if(checkTurn() && urlIndex.get() < urls.size()){
                    SettingConfig config=SettingState.getInstance().getConfig();
                    config.setUrlIndex(urlIndex.incrementAndGet());

                    if(CacheUtils.get(urlIndex.get())!=null){
                        content = CacheUtils.get(urlIndex.get());
                    }else{
                        content = getUrlData(word,urlIndex.get(),urls);
                        CacheUtils.add(urlIndex.get(),content);
                    }
                    config.setReadIndex(0);
                    index.set(-1);
                }else{
                    return;
                }
            }
            index.incrementAndGet();
            setText(content.get(index.get()));
            saveReadIndex();
        }
    }
    public static void clear(){
        anActionEvent.getPresentation().setText("Read");
        MyNotifier.notify(anActionEvent.getProject(),"");
    }
    private static void saveReadIndex() {
        SettingConfig config=SettingState.getInstance().getConfig();
        config.setReadIndex(index.get());
        SettingState.getInstance().setConfig(config);
    }
    public static void setText(String text){
        SettingConfig config=SettingState.getInstance().getConfig();
        if(config.getReadType() == 0){
            anActionEvent.getPresentation().setText(text);
        }else{
            MyNotifier.notify(anActionEvent.getProject(),text);
        }
    }
    private static boolean checkTurn(){
        if(path.contains("http") && urls!=null && urls.size() > 0 && urlDepth > 0){
            return true;
        }
        return false;
    }

    /**
     * 初始化内容
     * @param path
     * @param word
     * @param index
     * @return
     */
    private Map<String,List<String>> contentInit(String path,int word,int index,int urlDepth) {
        Map<String,List<String>> res = new HashMap<>();
        List<String> data = null;
        try {
            if(path.contains("http")){
                Map<String,List<String>> titles = JsoupHelp.init(path);
                List<String> urls = titles.get("url");
                if(urlDepth > 0){
                    data = new ArrayList<>(getUrlData(word, index, urls));
                }else{
                    data = titles.get("text");
                }
                res.put("directory",titles.get("text"));
                res.put("urls",urls);
            }else{
                data = LeanENForm.readFile(path,word);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        res.put("data",data);
        return res;
    }

    private static List<String> getUrlData(int word, int index,  List<String> urls) {
        String line = JsoupHelp.getText(urls.get(index),path);
        Vector<String> vector = new Vector<>();
        LeanENForm.extracted(line, word,vector);
        return vector;
    }

    public static synchronized void setContent(ContentVo vo){
        ContentAction.content = vo.getContent();
        ContentAction.urls = vo.getUrls();
        ContentAction.urlIndex.set(vo.getUrlIndex());
        ContentAction.urlDepth = vo.getUrlDepth();
        ContentAction.index.set(vo.getIndex());
        ContentAction.directory = vo.getDirectory();
        ContentAction.path = vo.getPath();
        if(ContentAction.index.get() == -1){
            setText("Read.");
            return;
        }
        setText(content.get(ContentAction.index.get()));
    }
    public static ContentVo getContent(){
        return new ContentVo(ContentAction.content
                ,ContentAction.directory
                ,ContentAction.urls
                ,ContentAction.index.get()
                ,ContentAction.urlIndex.get(),
                 ContentAction.urlDepth);
    }
}
